#!/bin/bash
set -Eeuo pipefail

# ===== Docker 可用性检查（保留）=====
if ! command -v docker >/dev/null 2>&1; then
  echo "未找到 docker 命令，请先安装/启用 Docker（群晖是 Container Manager）。"
  exit 1
fi
if ! docker info >/dev/null 2>&1; then
  echo "无法访问 Docker 守护进程（/var/run/docker.sock）。请用有权限的用户运行或检查权限。"
  exit 1
fi

# ===== 目录探测：/volume1 或 /mnt =====
if [ -d "/volume1/docker" ] && [ -d "/volume1/media" ]; then
  MEDIA_DIR="/volume1/media"
  CONFIG_DIR="/volume1/docker"
  echo "检测到 Synology：MEDIA_DIR=$MEDIA_DIR  CONFIG_DIR=$CONFIG_DIR"
elif [ -d "/mnt/docker" ] && [ -d "/mnt/media" ]; then
  MEDIA_DIR="/mnt/media"
  CONFIG_DIR="/mnt/docker"
  echo "检测到 Ugreen/极空间：MEDIA_DIR=$MEDIA_DIR  CONFIG_DIR=$CONFIG_DIR"
else
  echo "未找到 /volume1/{docker,media} 或 /mnt/{docker,media}，请先在共享文件夹创建 docker 与 media。"
  exit 1
fi

# ===== 工具函数 =====
get_uid_gid_from_path() {
  local p="$1"
  if [ -e "$p" ]; then
    ls -nd "$p" | awk '{print $3 ":" $4}'
  else
    echo ""
  fi
}

create_directory () {
  local dir="$1"
  if [ ! -d "$dir" ]; then
    mkdir -p "$dir"; echo "已创建: $dir"
  else
    echo "目录已存在: $dir"
  fi
  chown -R "${PUID:-$(id -u)}:${PGID:-$(id -g)}" "$dir" || true
  chmod -R 775 "$dir" || true
}

run_if_absent () {
  local name="$1"; shift
  if docker ps -a --format '{{.Names}}' | grep -wq "^${name}$"; then
    if docker ps --format '{{.Names}}' | grep -wq "^${name}$"; then
      echo "容器 $name 已在运行，跳过。"
    else
      echo "容器 $name 存在但未运行，尝试启动..."
      docker start "$name" >/dev/null
    fi
  else
    echo "启动容器 $name ..."
    "$@"
    echo "容器 $name 启动完成。"
  fi
}

# ===== PUID/PGID 自动探测（可被环境变量或标记文件覆盖）=====
PUID="${PUID:-}"
PGID="${PGID:-}"

# 1) 标记文件
if [ -z "${PUID}" ] || [ -z "${PGID}" ]; then
  if [ -f "$CONFIG_DIR/.puid" ] && [ -f "$CONFIG_DIR/.pgid" ]; then
    PUID="$(tr -d '[:space:]' < "$CONFIG_DIR/.puid")" || true
    PGID="$(tr -d '[:space:]' < "$CONFIG_DIR/.pgid")" || true
  fi
fi
# 2) sudo 入口用户
if [ -z "${PUID:-}" ] || [ -z "${PGID:-}" ]; then
  if [ -n "${SUDO_UID:-}" ] && [ -n "${SUDO_GID:-}" ]; then
    PUID="$SUDO_UID"; PGID="$SUDO_GID"
  fi
fi
# 3) 目录拥有者
if [ -z "${PUID:-}" ] || [ -z "${PGID:-}" ]; then
  owner_cfg="$(get_uid_gid_from_path "$CONFIG_DIR")"
  owner_med="$(get_uid_gid_from_path "$MEDIA_DIR")"
  if [ -n "$owner_cfg" ] && [ "${owner_cfg%%:*}" != "0" ]; then
    PUID="${owner_cfg%%:*}"; PGID="${owner_cfg##*:}"
  elif [ -n "$owner_med" ] && [ "${owner_med%%:*}" != "0" ]; then
    PUID="${owner_med%%:*}"; PGID="${owner_med##*:}"
  fi
fi
# 4) 回退当前用户
if [ -z "${PUID:-}" ] || [ -z "${PGID:-}" ]; then
  PUID="$(id -u)"; PGID="$(id -g)"
fi

TZ="Asia/Shanghai"
echo "最终使用的 PUID=$PUID  PGID=$PGID  TZ=$TZ"

# ===== 配置目录 =====
CONF_DIR_QBIT="$CONFIG_DIR/qbittorrent-config"
CONF_DIR_EMBY="$CONFIG_DIR/emby-config"
CONF_DIR_MP="$CONFIG_DIR/moviepilot-config"
CONF_DIR_JELLYFIN="$CONFIG_DIR/jellyfin-config"
CONF_DIR_NATFRP="$CONFIG_DIR/natfrp-config"

echo "创建配置目录..."
create_directory "$CONF_DIR_QBIT"
create_directory "$CONF_DIR_EMBY"
create_directory "$CONF_DIR_MP"
create_directory "$CONF_DIR_JELLYFIN"
create_directory "$CONF_DIR_NATFRP"

# ===== 媒体目录与子目录（精简）=====
MOVIE_DIR="$MEDIA_DIR/电影"
TV_DIR="$MEDIA_DIR/电视剧"
DOWNLOAD_DIR="$MEDIA_DIR/downloads"

create_directory "$MOVIE_DIR"
create_directory "$TV_DIR"
create_directory "$DOWNLOAD_DIR"

for d in "国语电影" "外语电影" "动画电影"; do
  create_directory "${MOVIE_DIR}/${d}"
done
for d in "国产剧" "欧美剧" "日韩剧" "纪录片" "动漫" "综艺"; do
  create_directory "${TV_DIR}/${d}"
done
create_directory "${DOWNLOAD_DIR}/电影"
create_directory "${DOWNLOAD_DIR}/电视剧"

# 仅对 downloads 赋权（防止下载保存失败）
chown -R "$PUID:$PGID" "$DOWNLOAD_DIR" || true
chmod -R 775 "$DOWNLOAD_DIR" || true

# ===== 端口（宿主机）=====
QBIT_WEB=8080
QBIT_BT=6881
MP_PORT=3000
EMBY_PORT=8096
JELLYFIN_PORT=8097   # 容器内 8096
NATFRP_PORT=7000     # 仅拉取不启动

# ===== 镜像（MoviePilot 改为 latest）=====
QBIT_IMG="0mwf6jyw7uafdy.xuanyuan.run/linuxserver/qbittorrent:latest"
EMBY_IMG="0mwf6jyw7uafdy.xuanyuan.run/emby/embyserver:latest"
MP_IMG="0mwf6jyw7uafdy.xuanyuan.run/jxxghp/moviepilot-v2:latest"
JELLYFIN_IMG="0mwf6jyw7uafdy.xuanyuan.run/jellyfin/jellyfin:latest"
NATFRP_IMG="0mwf6jyw7uafdy.xuanyuan.run/natfrp/frpc:latest"

echo "拉取镜像（显示官方进度条）..."
docker pull "$QBIT_IMG"
docker pull "$EMBY_IMG"
docker pull "$MP_IMG"
docker pull "$JELLYFIN_IMG"
docker pull "$NATFRP_IMG"   # 只拉取，不启动

# ===== 启动容器（bridge；不改 Web Station，不加 synology labels）=====
# qBittorrent（/downloads 与 /media 同盘，建议 WebUI 默认保存路径选 /downloads）
run_if_absent "qbittorrent" docker run -d \
  --name qbittorrent --network bridge \
  -e PUID="$PUID" -e PGID="$PGID" -e TZ="$TZ" \
  -p "${QBIT_WEB}:8080" \
  -p "${QBIT_BT}:${QBIT_BT}/tcp" \
  -p "${QBIT_BT}:${QBIT_BT}/udp" \
  -v "${CONF_DIR_QBIT}:/config" \
  -v "${DOWNLOAD_DIR}:/downloads" \
  -v "${MEDIA_DIR}:/media" \
  --restart unless-stopped \
  "$QBIT_IMG"

# MoviePilot（下载源 /downloads；目标库 /media；硬链接友好）
run_if_absent "moviepilot" docker run -d \
  --name moviepilot --network bridge \
  -e PUID="$PUID" -e PGID="$PGID" -e TZ="$TZ" \
  -p "${MP_PORT}:3000" \
  -v "${CONF_DIR_MP}:/config" \
  -v "${DOWNLOAD_DIR}:/downloads" \
  -v "${MEDIA_DIR}:/media" \
  --restart unless-stopped \
  "$MP_IMG"

# Emby（容器内 8096）
run_if_absent "emby" docker run -d \
  --name emby --network bridge \
  -e PUID="$PUID" -e PGID="$PGID" -e TZ="$TZ" \
  -p "${EMBY_PORT}:8096" \
  -v "${CONF_DIR_EMBY}:/config" \
  -v "${MEDIA_DIR}:/media" \
  --restart unless-stopped \
  "$EMBY_IMG"

# Jellyfin（容器内 8096；宿主 8097）
run_if_absent "jellyfin" docker run -d \
  --name jellyfin --network bridge \
  -e PUID="$PUID" -e PGID="$PGID" -e TZ="$TZ" \
  -p "${JELLYFIN_PORT}:8096" \
  -v "${CONF_DIR_JELLYFIN}:/config" \
  -v "${MEDIA_DIR}:/media" \
  --restart unless-stopped \
  "$JELLYFIN_IMG"

# natfrp：仅拉取，不启动（需要时手动：见注释）
# 示例：
# docker run -d --name natfrp --network bridge \
#   -p "${NATFRP_PORT}:7000" \
#   -v "${CONF_DIR_NATFRP}:/config" \
#   --restart unless-stopped \
#   "$NATFRP_IMG" -c /config/frpc.ini

echo "✅ 完成。"
echo "访问示例：qB http://NAS_IP:${QBIT_WEB} | MP http://NAS_IP:${MP_PORT} | Emby http://NAS_IP:${EMBY_PORT} | JF http://NAS_IP:${JELLYFIN_PORT}"